"""
试卷管理 - Django Admin 配置
管理试卷相关的后台界面
"""
from django.contrib import admin
from django.utils.html import format_html
from django.db.models import Count, Avg, Sum
from django.urls import reverse
from django.utils.safestring import mark_safe

from .models import (
    ExamPaperTemplate, ExamPaper, PaperSection, PaperQuestion,
    PaperAnalysis, PaperVersion
)


class PaperQuestionInline(admin.TabularInline):
    """试卷题目内联"""
    model = PaperQuestion
    extra = 0
    readonly_fields = ['question_info', 'question_type', 'question_difficulty']
    fields = [
        'question', 'section', 'question_number', 'score',
        'question_info', 'question_type', 'question_difficulty'
    ]

    def question_info(self, obj):
        """题目信息"""
        if obj.question:
            return f"{obj.question.title[:50]}..."
        return "-"
    question_info.short_description = '题目'

    def question_type(self, obj):
        """题目类型"""
        if obj.question:
            return obj.question.get_type_display()
        return "-"
    question_type.short_description = '类型'

    def question_difficulty(self, obj):
        """题目难度"""
        if obj.question:
            return obj.question.difficulty
        return "-"
    question_difficulty.short_description = '难度'

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        """外键字段过滤"""
        if db_field.name == 'section':
            # 只显示当前试卷的部分
            if 'object_id' in request.resolver_match.kwargs:
                paper_id = request.resolver_match.kwargs['object_id']
                kwargs['queryset'] = PaperSection.objects.filter(exam_paper_id=paper_id)
        return super().formfield_for_foreignkey(db_field, request, **kwargs)


@admin.register(ExamPaperTemplate)
class ExamPaperTemplateAdmin(admin.ModelAdmin):
    """试卷模板管理"""
    list_display = [
        'name', 'template_type', 'default_duration', 'default_total_score',
        'usage_count', 'is_active', 'is_public', 'creator', 'created_at'
    ]
    list_filter = [
        'template_type', 'is_active', 'is_public', 'created_at'
    ]
    search_fields = ['name', 'description', 'creator__real_name']
    readonly_fields = [
        'id', 'usage_count', 'creator', 'created_at', 'updated_at'
    ]

    fieldsets = (
        ('基本信息', {
            'fields': ('name', 'description', 'template_type')
        }),
        ('默认设置', {
            'fields': ('default_duration', 'default_total_score', 'default_passing_score')
        }),
        ('模板配置', {
            'fields': ('template_config',)
        }),
        ('状态控制', {
            'fields': ('is_active', 'is_public')
        }),
        ('统计信息', {
            'fields': ('usage_count',),
            'classes': ('collapse',)
        }),
        ('时间信息', {
            'fields': ('creator', 'created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )

    def get_queryset(self, request):
        return super().get_queryset(request).select_related('creator')

    def save_model(self, request, obj, form, change):
        if not change:  # 新建时设置创建者
            obj.creator = request.user
        super().save_model(request, obj, form, change)


@admin.register(ExamPaper)
class ExamPaperAdmin(admin.ModelAdmin):
    """试卷管理"""
    list_display = [
        'title', 'paper_type', 'status', 'generation_method',
        'question_count', 'total_score', 'duration',
        'creator', 'is_public', 'created_at'
    ]
    list_filter = [
        'paper_type', 'status', 'generation_method', 'is_public', 'created_at'
    ]
    search_fields = [
        'title', 'description', 'creator__real_name'
    ]
    readonly_fields = [
        'id', 'question_count', 'average_difficulty',
        'usage_count', 'creator', 'created_at', 'updated_at'
    ]
    inlines = [PaperQuestionInline]
    filter_horizontal = []

    fieldsets = (
        ('基本信息', {
            'fields': ('title', 'description', 'paper_type', 'status')
        }),
        ('生成信息', {
            'fields': ('template', 'generation_method', 'question_config')
        }),
        ('试卷设置', {
            'fields': ('duration', 'total_score', 'passing_score')
        }),
        ('题目信息', {
            'fields': ('questions', 'tags'),
            'classes': ('collapse',)
        }),
        ('统计信息', {
            'fields': ('question_count', 'average_difficulty', 'usage_count'),
            'classes': ('collapse',)
        }),
        ('审核信息', {
            'fields': ('reviewer', 'reviewed_at', 'review_notes'),
            'classes': ('collapse',)
        }),
        ('状态控制', {
            'fields': ('is_public',)
        }),
        ('时间信息', {
            'fields': ('creator', 'created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )

    def get_queryset(self, request):
        return super().get_queryset(request).select_related(
            'creator', 'template', 'reviewer'
        ).prefetch_related('paper_questions')

    def save_model(self, request, obj, form, change):
        if not change:  # 新建时设置创建者
            obj.creator = request.user
        super().save_model(request, obj, form, change)

    def get_readonly_fields(self, request, obj=None):
        if obj:  # 编辑时
            readonly = list(self.readonly_fields)
            if obj.status == 'published':
                readonly.extend(['title', 'paper_type', 'duration', 'total_score'])
            return readonly
        return self.readonly_fields

    def change_view(self, request, object_id=None, form_url='', extra_context=None):
        """自定义视图"""
        extra_context = extra_context or {}
        if object_id:
            try:
                paper = ExamPaper.objects.get(id=object_id)
                extra_context['show_paper_preview'] = True
                extra_context['paper_summary'] = {
                    'total_questions': paper.question_count,
                    'total_score': paper.total_score,
                    'duration': paper.duration,
                    'sections_count': paper.sections.count(),
                }
            except ExamPaper.DoesNotExist:
                pass
        return super().change_view(request, object_id, form_url, extra_context)


@admin.register(PaperSection)
class PaperSectionAdmin(admin.ModelAdmin):
    """试卷部分管理"""
    list_display = [
        'name', 'exam_paper_title', 'question_count',
        'section_score', 'time_limit', 'order'
    ]
    list_filter = ['exam_paper', 'time_limit']
    search_fields = ['name', 'description', 'exam_paper__title']
    readonly_fields = ['created_at', 'updated_at']

    def exam_paper_title(self, obj):
        """试卷标题"""
        return obj.exam_paper.title
    exam_paper_title.short_description = '试卷'

    def question_count(self, obj):
        """题目数量"""
        return obj.question_count
    question_count.short_description = '题目数'

    def get_queryset(self, request):
        return super().get_queryset(request).select_related('exam_paper')

    def get_form(self, request, obj=None, **kwargs):
        form = super().get_form(request, obj, **kwargs)
        if 'exam_paper' in form.base_fields:
            # 过滤试卷
            form.base_fields['exam_paper'].queryset = (
                ExamPaper.objects.all().select_related('creator')
            )
        return form


class PaperSectionInline(admin.TabularInline):
    """试卷部分内联"""
    model = PaperSection
    extra = 1
    fields = [
        'name', 'description', 'start_question', 'end_question',
        'section_score', 'time_limit', 'order'
    ]


@admin.register(PaperQuestion)
class PaperQuestionAdmin(admin.ModelAdmin):
    """试卷题目管理"""
    list_display = [
        'question_info', 'paper_title', 'section_name',
        'question_number', 'score', 'order'
    ]
    list_filter = ['exam_paper', 'section']
    search_fields = [
        'question__title', 'question__content',
        'exam_paper__title'
    ]
    readonly_fields = ['created_at', 'updated_at']

    def question_info(self, obj):
        """题目信息"""
        if obj.question:
            return f"{obj.question.title[:50]}..."
        return "-"
    question_info.short_description = '题目'

    def paper_title(self, obj):
        """试卷标题"""
        return obj.exam_paper.title
    paper_title.short_description = '试卷'

    def section_name(self, obj):
        """部分名称"""
        return obj.section.name if obj.section else "-"
    section_name.short_description = '部分'

    def get_queryset(self, request):
        return super().get_queryset(request).select_related(
            'exam_paper', 'section', 'question'
        )

    def get_form(self, request, obj=None, **kwargs):
        form = super().get_form(request, obj, **kwargs)
        if 'exam_paper' in form.base_fields:
            # 过滤试卷
            form.base_fields['exam_paper'].queryset = (
                ExamPaper.objects.all().select_related('creator')
            )
        if 'question' in form.base_fields:
            # 过滤题目
            form.base_fields['question'].queryset = (
                obj.question.__class__.objects.all().select_related('creator')
            )
        return form


@admin.register(PaperAnalysis)
class PaperAnalysisAdmin(admin.ModelAdmin):
    """试卷分析管理"""
    list_display = [
        'exam_paper_title', 'analysis_status',
        'average_difficulty', 'quality_score',
        'estimated_time', 'analyzed_at'
    ]
    list_filter = ['analysis_status', 'analyzed_at']
    search_fields = ['exam_paper__title']
    readonly_fields = [
        'id', 'exam_paper', 'difficulty_distribution',
        'knowledge_coverage', 'type_distribution',
        'quality_score', 'discrimination_index',
        'improvement_suggestions', 'analyzed_at',
        'created_at', 'updated_at'
    ]

    fieldsets = (
        ('基本信息', {
            'fields': ('exam_paper', 'analysis_status', 'analyzed_at')
        }),
        ('难度分析', {
            'fields': ('difficulty_distribution', 'average_difficulty')
        }),
        ('知识点分析', {
            'fields': ('knowledge_coverage', 'coverage_score')
        }),
        ('题型分析', {
            'fields': ('type_distribution',)
        }),
        ('质量指标', {
            'fields': ('quality_score', 'discrimination_index', 'estimated_time')
        }),
        ('改进建议', {
            'fields': ('improvement_suggestions',),
            'classes': ('collapse',)
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )

    def exam_paper_title(self, obj):
        """试卷标题"""
        return obj.exam_paper.title
    exam_paper_title.short_description = '试卷'

    def get_queryset(self, request):
        return super().get_queryset(request).select_related('exam_paper')

    def get_readonly_fields(self, request, obj=None):
        if obj:  # 编辑时，试卷分析的所有字段都只读
            return list(self.readonly_fields)
        return self.readonly_fields

    def change_view(self, request, object_id=None, form_url='', extra_context=None):
        """自定义视图"""
        extra_context = extra_context or {}
        if object_id:
            try:
                analysis = PaperAnalysis.objects.get(id=object_id)
                extra_context['show_analysis_chart'] = True
                extra_context['analysis_summary'] = {
                    'average_difficulty': analysis.average_difficulty,
                    'quality_score': analysis.quality_score,
                    'estimated_time': analysis.estimated_time,
                }
            except PaperAnalysis.DoesNotExist:
                pass
        return super().change_view(request, object_id, form_url, extra_context)


@admin.register(PaperVersion)
class PaperVersionAdmin(admin.ModelAdmin):
    """试卷版本管理"""
    list_display = [
        'exam_paper_title', 'version_number',
        'is_current', 'created_by_name', 'created_at'
    ]
    list_filter = ['is_current', 'created_at']
    search_fields = [
        'exam_paper__title', 'version_number', 'created_by__real_name'
    ]
    readonly_fields = [
        'id', 'exam_paper', 'version_number', 'paper_snapshot',
        'changes', 'created_by', 'created_at', 'updated_at'
    ]

    fieldsets = (
        ('基本信息', {
            'fields': ('exam_paper', 'version_number', 'version_notes')
        }),
        ('版本信息', {
            'fields': ('is_current', 'changes')
        }),
        ('快照数据', {
            'fields': ('paper_snapshot',),
            'classes': ('collapse',)
        }),
        ('时间信息', {
            'fields': ('created_by', 'created_at', 'updated_at'),
            'classes': ('collapse',)
        })
    )

    def exam_paper_title(self, obj):
        """试卷标题"""
        return obj.exam_paper.title
    exam_paper_title.short_description = '试卷'

    def created_by_name(self, obj):
        """创建者姓名"""
        return obj.created_by.real_name if obj.created_by else "-"
    created_by_name.short_description = '创建者'

    def get_queryset(self, request):
        return super().get_queryset(request).select_related(
            'exam_paper', 'created_by'
        )

    def get_readonly_fields(self, request, obj=None):
        if obj:  # 编辑时，版本管理模块的所有字段都只读
            readonly = list(self.readonly_fields)
            if not request.user.is_admin_user:
                readonly.extend(['version_number', 'paper_snapshot'])
            return readonly
        return self.readonly_fields

    def save_model(self, request, obj, form, change):
        if not change:  # 新建时设置创建者
            obj.created_by = request.user
        super().save_model(request, obj, form, change)

    def change_view(self, request, object_id=None, form_url='', extra_context=None):
        """自定义视图"""
        extra_context = extra_context or {}
        if object_id:
            try:
                version = PaperVersion.objects.get(id=object_id)
                extra_context['show_version_comparison'] = True
                extra_context['version_info'] = {
                    'is_current': version.is_current,
                    'created_by': version.created_by.real_name if version.created_by else None,
                    'changes_count': len(version.changes) if version.changes else 0,
                }
            except PaperVersion.DoesNotExist:
                pass
        return super().change_view(request, object_id, form_url, extra_context)


# 自定义Admin站点标题
admin.site.site_header = 'AI-SOES 试卷管理后台'
admin.site.site_title = 'AI-SOES 试卷管理'
admin.site.index_title = '智能在线考试系统 - 试卷管理模块'